﻿using MediatR;
using PublicCommon;
using T_vehicle.Domain;
using T_vehicle.Infrastructure.Impl;
using T_vehicle.Infrastructure.Interfacec;
using T_vehicle.Read.API.Application.Command.MaintenanceCommand;

namespace T_vehicle.Read.API.Application.CommandHandlers.MaintenanceCommandHandlers
{
    public class GetMaintenanceCommandHandlers:IRequestHandler<GetMaintenanceCommand,PageResult<Maintenance>>
    {
        private readonly IMaintenanceRepository maintenanceRepository;

        public GetMaintenanceCommandHandlers(IMaintenanceRepository maintenanceRepository)
        {
            this.maintenanceRepository = maintenanceRepository;
        }

        public async Task<PageResult<Maintenance>> Handle(GetMaintenanceCommand request, CancellationToken cancellationToken)
        {
            var list = maintenanceRepository.GetAllAsync().Result.Where(x=>x.IsDel==false).AsQueryable();
            if (!string.IsNullOrEmpty(request.LicenNumber))
            {
                list = list.Where(x => x.LicenNumber.Contains(request.LicenNumber));
            }
            if (!string.IsNullOrEmpty(request.Head))
            {
                list = list.Where(x => x.Head.Contains(request.Head));
            }
            if (!string.IsNullOrEmpty(Convert.ToString(request.MaintenanceDateNow)))
            {
                list = list.Where(x =>Convert.ToString(x.MaintenanceDateNow) == Convert.ToString(request.MaintenanceDateNow));
            }

            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
            var res = list.Skip(request.pageIndex-1*request.pageSize).Take(request.pageSize).ToList();
            return new PageResult<Maintenance>
            {
                TotalCount = totalCount,
                PageCount = pageCount,
                List = res
            };

        }
    }
}
